package com.CMUBiS.PageServlets;
import java.io.*;
import java.text.DateFormat;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;

import com.CMUBiS.Data.Error;
import com.CMUBiS.Data.Footer;
import com.CMUBiS.Data.GlobalVars;
import com.CMUBiS.Data.Header;
import com.CMUBiS.PageControllers.*;
import com.CMUBiS.util.StopWatch;

/**
 * This servlet is a blank example
 * 
 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
 * @version 0.1
 * @since 0.1
 * @date 04/05/2011
 * 
 */
@WebServlet(name="SellItemServlet", urlPatterns="/sellitem")
public class SellItemServlet extends HttpServlet {
	
	private static final long serialVersionUID = 6477841456628458743L;
	private static final String EMPTY = "";
	private static final String title = "Sell Item";
	
	/**
	 * Get the page, calls the page to be made
	 * We used to check the parameters in here, but I moved it to a controller object to keep the logic away from the layout
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(GlobalVars.isHTML4){
			makePage(request, response, Boolean.FALSE);
		}else{
			PrintWriter out = response.getWriter();
			response.setContentType("application/json");
			@SuppressWarnings("deprecation")
			Boolean registerUser = GlobalVars.db.insertItem(Integer.parseInt(request.getParameter("userID")), request.getParameter("name"), request.getParameter("description"), Float.parseFloat(request.getParameter("startPrice")), Float.parseFloat(request.getParameter("reservePrice")), Float.parseFloat(request.getParameter("buyNowPrice")), Integer.parseInt(request.getParameter("quantity")),  new Date(Long.parseLong(request.getParameter("endDate"))), Integer.parseInt(request.getParameter("categoryID")));
			if(registerUser){
				out.println("{\"sellitem\":\"true\"}");
				System.out.println("Item posted!");
			}else{
				out.println("{\"sellitem\":\"false\"}");
				System.out.println("Item not posted...");
			}
		}
	}
	
	
	
	/**
	 * Get the page, we can just pass this to doPost since the client generator will be posting userIDs and authTokens all the time
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(GlobalVars.isHTML4){
			makePage(request, response, Boolean.TRUE);
		}else{
			PrintWriter out = response.getWriter();
			response.setContentType("application/json");
			@SuppressWarnings("deprecation")
			Boolean registerUser = GlobalVars.db.insertItem(Integer.parseInt(request.getParameter("userID")), request.getParameter("name"), request.getParameter("description"), Float.parseFloat(request.getParameter("startPrice")), Float.parseFloat(request.getParameter("reservePrice")), Float.parseFloat(request.getParameter("buyNowPrice")), Integer.parseInt(request.getParameter("quantity")),  new Date(Long.parseLong(request.getParameter("endDate"))), Integer.parseInt(request.getParameter("categoryID")));
			if(registerUser){
				out.println("{\"sellitem\":\"true\"}");
				//System.out.println("Item posted!");
			}else{
				out.println("{\"sellitem\":\"false\"}");
				//System.out.println("Item not posted...");
			}
		}
	}
	
	/**
	 * This method starts the page timer, writes the header, creates the HTML for the page, writes the stats, and the footer
	 * 
	 * @param request The incoming user request
	 * @param response  The out going user response
	 * @throws ServletException
	 * @throws IOException
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void makePage(HttpServletRequest request, HttpServletResponse response, Boolean isGet)  throws ServletException, IOException {
		if(request !=null && response != null){
			// Do the timer if we are collecting stats
			StopWatch timer;
			if(GlobalVars.collectStats){
				timer = new StopWatch();
				timer.start();
			}
			
			// Create a new page controller for this page, it will get and process the data
			SellItemController vars = new SellItemController();
			vars.checkInputs(request);
			
			// If there are no errors we can try and insert the item
			if(vars.getErrors().size()==0){
				if(vars.insertItem()){
					timer.stop();
					response.sendRedirect(vars.getRedirectURL());
				}
			}
			
			// We are using PrintWriter to be friendly to the international community. PrintWrite auto-converts coding
			PrintWriter out = response.getWriter();
	
			// Set the return type
			response.setContentType("text/html");
			
			// Write the page header
			Header.writeHeader(out, title, vars.getUserIDString(), vars.getAuthTokenString());
			
			// If the output is to be suppressed then we'll redirect the output
			if(vars.getSuppressOutput())
				out = new PrintWriter(GlobalVars.blackHole);
			
			// Do HTML4 or 5 depending on the global variables
			if(GlobalVars.isHTML4)
				createHTML4(out, vars, isGet);
			else
				createHTML5(out, vars, isGet);
			
			// Redirect the output to start writing the the user again in case we were putting it in the black hole
			out = response.getWriter();
			
			/*
			 * Output any errors. These don't need to be too pretty since we hope there isn't any!
			 * We put them here to help with debug and info, the page above should show pretty ones for users
			 */
			if(GlobalVars.printAllErrors){
				out.println("<BR />Errors: " + vars.getErrors().size());
				for(Error error: vars.getErrors())
					out.println("<BR />" + error.getErrorNumber() + " " +error.toString());
			}
			
			/*
			 * Process the page time
			 */
			if(GlobalVars.collectStats){
				timer.stop();
				vars.setTotalTime(timer.getTimeTaken());
				GlobalVars.addStats(request, out, vars);
			}
			
			// Write the page footer
			Footer.writeFooter(out);
		}
	}
	
	/**
	 * Creates the HTML4 version of the website
	 * 
	 * @param request The incoming request
	 * @param response The response sent to the user
	 * @param out The out writer to write the HTML to
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void createHTML4(PrintWriter out, SellItemController vars, Boolean isGet){
		if(out != null && vars != null)
		try{
			// Get the data needed to display the page
			vars.getHTML4Data();
			vars.processHTML4();
			
			/*
			 * Make the input form
			 */
			out.println("<form name=\"register_user\" action=\"sellitem?userID=" + vars.getUserIDString() + "&authToken=" + vars.getAuthTokenString() + "\" method=\"POST\">");
			out.println("<div id=\"center\">");	
			
			out.println("<div id=\"floatright\">Item Name: </div>");
			out.println("<div id=\"floatcenter\"> <input type=\"text\" name=\"name\" size=\"50\" value=\""+ vars.getName() + "\"/> </div>");
			
			out.println("<div id=\"floatright\">Description: </div>");
			out.println("<div id=\"floatcenter\"> <input type=\"text\" name=\"description\" size=\"50\" value=\""+ vars.getDescription() + "\"/> </div>");
			
			out.println("<div id=\"floatright\">Start Price: </div>");
			out.println("<div id=\"floatcenter\"> <input type=\"text\" name=\"startPrice\" size=\"7\" value=\""+ vars.getStartPrice() + "\"/> </div>");
			
			out.println("<div id=\"floatright\">Reserve Price </div>");
			out.println("<div id=\"floatcenter\"> <input type=\"text\" name=\"reservePrice\" size=\"7\" value=\""+ vars.getReservePrice() + "\"/> </div>");
			
			out.println("<div id=\"floatright\">Buy Now Price: </div>");
			out.println("<div id=\"floatcenter\"> <input type=\"text\" name=\"buyNowPrice\" size=\"7\" value=\""+ vars.getBuyNowPrice() + "\"/> </div>");
			
			out.println("<div id=\"floatright\">Quantity: </div>");
			out.println("<div id=\"floatcenter\"> <input type=\"text\" name=\"quantity\" size=\"5\" value=\""+ vars.getQuantity() + "\"/> </div>");
			
			out.println("<div id=\"floatright\">Category: </div>");
			out.println("<div id=\"floatcenter\">");
			out.println("<select name=\"categoryID\">");
			
			String[] categorySelections = vars.getCategorySelections();
			if(categorySelections != null)
				for(String selection: categorySelections)
					out.println(selection);
			
			out.println("</select>");
			out.println("</div>");
			
			out.println("<div id=\"floatright\">End Date (yyyy-MM-dd HH:mm:ss): </div>");
			out.println("<div id=\"floatcenter\"> <input type=\"text\" name=\"endDate\" size=\"20\" value=\""+ GlobalVars.sdf.format(vars.getEndDate()) + "\"/> </div>");
			
			out.println("<div id=\"floatright\"><input type=\"submit\" value=\"Sell\"></div>");
			
			out.println("</div>");
			out.println("</form>");
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * Creates the HTML5 version of the website
	 * 
	 * @param request The incoming request
	 * @param response The response sent to the user
	 * @param out The out writer to write the HTML to
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void createHTML5(PrintWriter out, SellItemController vars, Boolean isGet){
		if(out != null && vars != null)
		try{
			// Get the data needed to display the page
			vars.getHTML5Data();
			vars.processHTML5();
			
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
}
